package com.design.util;

import com.design.config.GameFile;

import javax.sound.sampled.*;
import java.io.File;

public class Music extends Thread {
    private void play(File file){
        AudioInputStream as;
        try {
            as = AudioSystem.getAudioInputStream(file);//音频文件在项目根目录的img文件夹下
            AudioFormat format = as.getFormat();
            SourceDataLine sdl = null;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            sdl = (SourceDataLine) AudioSystem.getLine(info);
            sdl.open(format);
            sdl.start();
            int nBytesRead = 0;
            byte[] abData = new byte[10];
            while (nBytesRead != -1) {
                nBytesRead = as.read(abData, 0, abData.length);
                if (nBytesRead >= 0)
                    sdl.write(abData, 0, nBytesRead);
            }
            //关闭SourceDataLine
            sdl.drain();
            sdl.close();
        }catch ( Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        File[] files = new File(GameFile.MUSIC_DIR).listFiles();
        if(files == null){
            return;
        }
        while(true){
            this.play(files[(int)(Math.random() * files.length)]);
        }
    }
}
